//
//  HJStatusViewModel.swift
//  Weibo
//
//  Created by 韩佳 on 16/4/20.
//  Copyright © 2016年 ddg. All rights reserved.
//

import UIKit
import SDWebImage

class HJStatusViewModel: NSObject {
    
    var status: HJStatus?{
        didSet{
            setMemberImage()
            setSouceText()
            if let s = status?.retweeted_status{
                if let name = s.user?.name, content = s.text{
                    retweentText = "@\(name):\(content)"
                }
            }
            //设置配图大小
            retweetPictureViewSize = calcPictureSize(status?.retweeted_status?.pic_urls)
            originalPictureViewSize = calcPictureSize(status?.pic_urls)
//            setupCreatAtText()
            creatDate = sinaDate(status?.created_at)
        }
    }
    //会员等级图像
    var memberImage:UIImage?
    //转发微博文本
    var retweentText:String?
    //来源
    var sourceText:String?
    //配图整体大小
    var retweetPictureViewSize:CGSize = CGSizeZero
    var originalPictureViewSize:CGSize = CGSizeZero
    var creatAtText:String?{
        return setupCreatAtText(creatDate ?? NSDate())
    }
    private var creatDate:NSDate?
    func updateSingleImagePictureViewSize(){
        retweetPictureViewSize = calcSingleImageSize(status?.retweeted_status?.pic_urls)
        originalPictureViewSize = calcSingleImageSize(status?.pic_urls)
    }
    //计算单张图片
    private func calcSingleImageSize(pic_urls:[HJStatusPhontoInfo]?)->CGSize{
        guard let imgUrlString = pic_urls?.first?.thumbnail_pic else{
            return CGSizeZero
        }
        if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(imgUrlString){
            //SDWebImage会自动根据缩放比调整图片大小,我们需要将其恢复
            let scale = UIScreen.mainScreen().scale
            var size = CGSizeMake(image.size.width * scale , image.size.height * scale)
            
            if size.width < 50 {
                let height = 50 / size.width * size.height
                size.width = 50
                size.height = height > 100 ? 100 : height
            }
            return size
        }
        return CGSizeZero
    }
    //计算配图view大小
    private func calcPictureSize(pic_urls:[HJStatusPhontoInfo]?)->CGSize{
        let count = pic_urls?.count ?? 0
        if count == 0 {
            return CGSizeZero
        }
        //列数
        let col = count == 4 ? 2 : (count > 3 ? 3 : count)
        //行数
        let row = (count - 1) / 3 + 1
        
        let margin: CGFloat = HJStatusPictureItemMargin
        let itemHW:CGFloat = HJStatusPictureItemWH
        
        let width = itemHW * CGFloat(col) + margin * CGFloat(col - 1)
        let height = itemHW * CGFloat(row) + margin * CGFloat(row - 1)
        
        return CGSize(width: width, height: height)
    }
    /**
     来源
     */
    func setSouceText(){
        //<a href=\"http://app.weibo.com/t/feed/5B6hUc\" rel=\"nofollow\">iPhone 6s Plus</a>
        guard let s = status?.source else{
            return
        }
        if let beganIndex = s.rangeOfString("\">")?.endIndex,endIndex = s.rangeOfString("</")?.startIndex{
            let str = s.substringWithRange(beganIndex..<endIndex)
            sourceText = "来自 \(str)"
        }
    }
    //会员图片
    func setMemberImage(){
        guard let mbrank = status?.user?.mbrank where mbrank > 0 && mbrank < 7 else{
            memberImage = nil
            return
        }
        memberImage = UIImage(named: "common_icon_membership_level\(mbrank)")
    }
    //设置微博时间
    private func setupCreatAtText(creatDate:NSDate) ->String{

//        //创建时间格式化器
        let fm = NSDateFormatter();
        fm.locale = NSLocale(localeIdentifier: "en")
        let calendar = NSCalendar.currentCalendar()
        
        if isDateInThisYear(creatDate){//今年
            if calendar.isDateInToday(creatDate){//今天
                let currentDate = NSDate()
                let timeInterval = currentDate.timeIntervalSinceDate(creatDate)
                if timeInterval < 60 {//一份钟内
                    return "刚刚"
                }else if timeInterval < 3600 {//一小时内
                    return "\(Int(timeInterval / 60))分钟前"
                }else{//大于一小时
                    return "\(Int(timeInterval / 3600))小时前"
                }
            }else if calendar.isDateInYesterday(creatDate){//昨天
                fm.dateFormat = "昨天 HH:mm"
                return fm.stringFromDate(creatDate)
            }else{
                fm.dateFormat = "MM-dd HH:mm"
                return fm.stringFromDate(creatDate)
            }
        }else{//不是今年
            fm.dateFormat = "yyyy-MM-dd HH:mm"
            return fm.stringFromDate(creatDate)
        }
        
    }
    //是否是今年
    private func isDateInThisYear(targetDate:NSDate) ->Bool{
        
        let fm = NSDateFormatter()
        fm.dateFormat = "yyyy"
        let currentYear = fm.stringFromDate(NSDate())
        let targetYear = fm.stringFromDate(targetDate)
        return currentYear == targetYear
    }
    private func sinaDate(createAt:String?) -> NSDate?{
        guard let creat_at = status?.created_at else{
            return nil
        }
        //创建时间格式化器
        let fm = NSDateFormatter();
        //设置时间格式化器的转化格式   Sun Nov 22 11:25:56 +0800 2015
        fm.locale = NSLocale(localeIdentifier: "en")//设置时区
        fm.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        let creatDate = fm.dateFromString(creat_at)!
        return creatDate
    }
}
